#pragma once
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <thread>
#include <vector>
#include <functional>
#include <future>

#include <iostream>
namespace mymq
{
    class ThreadPool
    {
    public:
        using Functor = std::function<void()>;
        using ptr = std::shared_ptr<ThreadPool>;
    public:
        ThreadPool(int thread_count = 1)
            : _stop(false)
        {
            for (int i = 0; i < thread_count; i++)
            {
                _threads.emplace_back(&ThreadPool::entry, this);
            }
        }
        ~ThreadPool()
        {
            Stop();
        }
        void Stop()
        {
            if (_stop) return;
            _stop = true;
            std::unique_lock<std::mutex> lock(_mtx);
            _cond.notify_all();
            for (auto &thread : _threads)
                thread.join();
        }
        template <typename Fn, typename... Args>
        auto Push(Fn&& func, Args&& ...args) -> std::future<decltype(func(args...))>
        {
            using return_type = decltype(func(args...));
            auto myfunc = std::bind(std::forward<Fn>(func), std::forward<Args>(args)...);
            auto ptask = std::make_shared<std::packaged_task<return_type()>>(myfunc);
            std::future<return_type> fu = ptask->get_future();
            {
                std::unique_lock<std::mutex> lock(_mtx);
                if (!_stop)
                {
                    _tasks.emplace_back([ptask](){
                        (*ptask)();
                    });
                }
                _cond.notify_one();
            }
            return fu;
        }
    private:
        void entry()
        {
            while (!_stop)
            {
                std::vector<Functor> tasks;
                {
                    std::unique_lock<std::mutex> lock(_mtx);
                    _cond.wait(lock, [this]()
                            { return _stop || !_tasks.empty(); });
                    if (_stop && _tasks.empty()) return;
                    tasks.swap(_tasks);
                }
                for (const auto &task : tasks)
                {
                    task();
                }
            }
        }

    private:
        std::mutex _mtx;
        std::condition_variable _cond;
        std::atomic<bool> _stop;
        std::vector<std::thread> _threads;
        std::vector<Functor> _tasks;
    };
}